from django.contrib.auth.backends import ModelBackend
from django.db.models import Q

from user.models import UserModel


class CustomBackends(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        if username is None:
            username = kwargs.get(UserModel.USERNAME_FIELD)
        if username is None or password is None:
            return
        user = UserModel.objects.filter(Q(username=username) | Q(phone=username) |Q(email=username)).first()

        if user and user.check_password(password):
            return user
        else:
            return